package com.xc.ksxt.controller;

import com.alibaba.fastjson.JSON;
import com.xc.common.object.LayuiTableResponse;
import com.xc.common.object.PageInfo;
import com.xc.common.object.ResponseEntity;
import com.xc.common.object.TreeObject;
import com.xc.common.tool.Helper;
import com.xc.db.tables.Chapter;
import com.xc.db.tables.Pian;
import com.xc.ksxt.entity.ChapterEntity;
import com.xc.ksxt.entity.PianEntity;
import com.xc.ksxt.service.ChapterService;
import com.xc.ksxt.service.PianService;
import com.xc.ksxt.vo.ChapterVO;
import com.xc.sys.service.SysUserService;
import com.xc.sys.vo.SysUserVO;
import org.apache.commons.lang3.StringUtils;

import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/chapter")
public class ChapterController {

    @Autowired
    private DSLContext dsl;
    @Autowired
    private PianService pianService;
    @Autowired
    private ChapterService chapterService;
    private Chapter CHAPTER = Chapter.CHAPTER.as("CHAPTER");
    private Pian PIAN = Pian.PIAN.as("PIANTB");
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
    @RequestMapping({"/getPageList"})
    public LayuiTableResponse<ChapterVO> getPageList(HttpServletRequest request) {
        LayuiTableResponse<ChapterVO> ltr = new LayuiTableResponse<>();
        Condition cond = CHAPTER.DEL_FLAG.notEqual(-1);
        String name = request.getParameter("name");
        String pianId = request.getParameter("pianId");
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        Integer page = Integer.valueOf(request.getParameter("page"));
        if (StringUtils.isNotBlank(name)) {
            cond = cond.and(CHAPTER.NAME.like("%"+name+"%"));
        }
        if (pianId!=null&&StringUtils.isNotEmpty(pianId)&&!pianId.equals("null")) {
            cond = cond.and(CHAPTER.PIAN_ID.eq(Long.valueOf(pianId)));
        }
        Long count = chapterService.count(cond);
        ltr.setCount(count);
        PageInfo<ChapterEntity> pageInfo = new PageInfo<>(limit, page);
        Result<Record> list = chapterService.select(cond, pageInfo,CHAPTER.ORDERNO.asc(),CHAPTER.NAME.asc(),CHAPTER.CREATE_TIME.desc());
        List<ChapterVO> chapterEntityList = list.into(ChapterVO.class);
        for (ChapterVO chapterEntity : chapterEntityList){
            setTxt(chapterEntity);
        }
        ltr.setData(chapterEntityList);
        return ltr;
    }
    @RequestMapping({"/getList"})
    public LayuiTableResponse<ChapterVO> getList(HttpServletRequest request) {
        LayuiTableResponse<ChapterVO> ltr = new LayuiTableResponse<>();
        Condition cond = CHAPTER.DEL_FLAG.notEqual(-1);
        String name = request.getParameter("name");
        String pianId = request.getParameter("pianId");
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        Integer page = Integer.valueOf(request.getParameter("page"));
        if (StringUtils.isNotBlank(name)) {
            cond = cond.and(CHAPTER.NAME.like("%"+name+"%"));
        }
        if (StringUtils.isNotBlank(pianId)) {
            cond = cond.and(CHAPTER.PIAN_ID.eq(Long.valueOf(pianId)));
        }
        Long count = chapterService.count(cond);
        ltr.setCount(count);

        PageInfo<ChapterEntity> pageInfo = new PageInfo<>(limit, page);
        Result<Record> list = chapterService.select(cond, pageInfo,CHAPTER.ORDERNO.asc(),CHAPTER.NAME.asc(),CHAPTER.CREATE_TIME.desc());
        List<ChapterVO> chapterEntityList = list.into(ChapterVO.class);
        List<ChapterVO> data = new ArrayList<>();
        for (ChapterVO chapterEntity : chapterEntityList){
            setTxt(chapterEntity);
            chapterEntity.setParentId(chapterEntity.getPianId());
            data.add(chapterEntity);
        }
        List<PianEntity> pians = pianService.select(PIAN.DEL_FLAG.notEqual(-1), PIAN.ORDERNO.asc());
        for (PianEntity pian : pians) {
            ChapterVO v = new ChapterVO();
            v.setId(pian.getId());
            v.setName(pian.getName());
            v.setPianId("");
            v.setOrderno(pian.getOrderno());
            data.add(v);
        }
//        System.out.println(chapterEntityList.size());
//        System.out.println(JSON.toJSONString(data,true));
        ltr.setData(data);
        return ltr;
    }

    private void setTxt(ChapterVO chapterEntity) {
        SysUserVO user = SysUserService.getFrameCaches(chapterEntity.getCreateUserId());
        chapterEntity.setCreateUserName(user==null?"":user.getName());
        if(chapterEntity.getPianId()!=null){
            PianEntity pian = PianService.getFromCaches(chapterEntity.getPianId());
            chapterEntity.setPianName(pian==null?"":pian.getName());
        }
    }

    @RequestMapping({ "/getFullTree" })
    public List<TreeObject> getFullTree(String pid, HttpServletRequest request) {
        List<TreeObject> list = new ArrayList<>();
        joinFullTreeNode(pid, list);
        return list;
    }
    private void joinFullTreeNode(String parentId, List<TreeObject> list) {
        List<PianEntity> pians = pianService.select(PIAN.DEL_FLAG.notEqual(-1),PIAN.ORDERNO.asc());
        for (PianEntity r : pians) {
            String id = r.getId();
            String name = r.getName();
            TreeObject treeObject = new TreeObject();
            treeObject.setName(name);
            treeObject.setType(1);
            treeObject.setId(id + "");
            List<TreeObject> children = new ArrayList<>();
            List<ChapterEntity> result = chapterService.select(CHAPTER.DEL_FLAG.notEqual(-1).and(CHAPTER.PIAN_ID.eq(Long.valueOf(id))), CHAPTER.ORDERNO.asc());
            if (!result.isEmpty()) {
                for (ChapterEntity r2 : result) {
                    String id2 = r2.getId();
                    String name2 = r2.getName();
                    TreeObject treeObject2 = new TreeObject();
                    treeObject2.setName(name2);
                    treeObject2.setType(2);
                    treeObject2.setId(id2);
                    treeObject2.setPid(id);
                    children.add(treeObject2);
                }
                treeObject.setIsParent(true);
                treeObject.setChildren(children);
            }


            list.add(treeObject);
        }

    }
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
    @RequestMapping({"/getById"})
    public ChapterVO getById(Long id) {
        Record r = chapterService.getRecordById(id);
        ChapterVO v = r.into(ChapterVO.class);
        setTxt(v);
        return v;
    }
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.POST})
    @RequestMapping({"/save"})
    public ResponseEntity<ChapterEntity> save(@RequestBody HashMap<String,String> params, HttpServletRequest request) {
        ResponseEntity<ChapterEntity> res = new ResponseEntity<>();
        ChapterEntity chapterEntity = Helper.map2Bean(new ChapterEntity(), params);
        chapterService.save(chapterEntity);
        return res;
    }
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.POST})
    @RequestMapping({"/delete"})
    public LayuiTableResponse<ChapterEntity> delete(@RequestBody Map<String,String> params) {
        String idstr = params.get("ids");
        Long[] idarr = Helper.str2longArr(idstr);
        LayuiTableResponse<ChapterEntity> ltr = new LayuiTableResponse<>();
        for (Long id : idarr) {
            ChapterEntity m = chapterService.getEntityById(id);
            m.setDelFlag(-1);
            chapterService.update(m);
        }
        return ltr;
    }

}
